package com.andnux.android.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.andnux.android.MainApp;
import com.andnux.android.R;
import com.andnux.android.data.ChatSession;
import com.andnux.android.data.PageData;
import com.andnux.android.data.SystemUsers;
import com.andnux.android.databinding.ActivityMainBinding;
import com.andnux.android.fragment.HomeFragment;
import com.andnux.android.fragment.MineFragment;
import com.andnux.android.fragment.SessionFragment;
import com.andnux.android.fragment.WorksFragment;
import com.andnux.android.network.DesignCloudApi;
import com.andnux.android.network.NotNullConsumer;
import com.andnux.android.network.Result;
import com.andnux.android.network.RetrofitClient;
import com.andnux.android.network.WebSocketManager;
import com.google.android.material.bottomnavigation.BottomNavigationItemView;
import com.google.android.material.bottomnavigation.BottomNavigationMenuView;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends BaseActivity<ActivityMainBinding> implements BottomNavigationView.OnNavigationItemSelectedListener {

    private List<Class<? extends Fragment>> fragmentList;
    private FragmentStateAdapter adapter;

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            loadData();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fragmentList = new ArrayList<>();
        fragmentList.add(HomeFragment.class);
        fragmentList.add(WorksFragment.class);
        fragmentList.add(SessionFragment.class);
        fragmentList.add(MineFragment.class);

        SystemUsers users = MainApp.getApp().getSystemUsers();
        if (users != null) {
            SharedPreferences preferences = MainApp.getApp().getSharedPreferences("config", Context.MODE_PRIVATE);
            String url = preferences.getString("url", "");
            WebSocketManager.getInstance().init(String.format(Locale.CHINA,
                    "ws://%s:8080/design-cloud/websocket", url) + "/" + users.getId());
        }

        MenuItem item = binding.navView.getMenu().getItem(1);
        if (users != null) {
            String role = users.getRole();
            if ("1".contentEquals(role)) {
                item.setTitle("需求");
            } else {
                item.setTitle("作品");
            }
        }
        adapter = new FragmentStateAdapter(this) {
            @Override
            public int getItemCount() {
                return fragmentList.size();
            }

            @NonNull
            @NotNull
            @Override
            public Fragment createFragment(int position) {
                try {
                    return fragmentList.get(position).newInstance();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        };
        binding.viewPager.setAdapter(adapter);
        binding.viewPager.setOffscreenPageLimit(fragmentList.size());
        binding.viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                switch (position) {
                    case 0:
                        binding.navView.setSelectedItemId(R.id.item1);
                        break;
                    case 1:
                        binding.navView.setSelectedItemId(R.id.item2);
                        break;
                    case 2:
                        binding.navView.setSelectedItemId(R.id.item3);
                        break;
                    case 3:
                        binding.navView.setSelectedItemId(R.id.item4);
                        break;
                }
            }
        });
        binding.navView.setOnNavigationItemSelectedListener(this);

        String[] permissions = {
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE
        };
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(permissions, 0x88);
        }

        IntentFilter filter = new IntentFilter();
        filter.addAction("message");
        registerReceiver(receiver, filter);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }


    @Override
    @SuppressLint("all")
    public boolean onNavigationItemSelected(@NonNull @NotNull MenuItem item) {
        int itemId = item.getItemId();
        switch (itemId) {
            case R.id.item1:
                binding.viewPager.setCurrentItem(0, false);
                break;
            case R.id.item2:
                binding.viewPager.setCurrentItem(1, false);
                break;
            case R.id.item3:
                binding.viewPager.setCurrentItem(2, false);
                break;
            case R.id.item4:
                binding.viewPager.setCurrentItem(3, false);
                break;
        }
        return true;
    }

    @Override
    public void onMessage(String text) {
        super.onMessage(text);
        loadData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
    }

    private void loadData() {
        SystemUsers users = MainApp.getApp().getSystemUsers();
        DesignCloudApi api = RetrofitClient.getInstance().getServerApi();
        addDisposable(api.chatSessionPage(0, 1000, String.valueOf(users.getId()), null)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new NotNullConsumer<Result<PageData<List<ChatSession>>>>() {
                    @Override
                    public void onSuccess(Result<PageData<List<ChatSession>>> result) {
                        int count = 0;
                        List<ChatSession> list = result.getData().getList();
                        for (ChatSession session : list) {
                            count += session.getToBeReadMessCount();
                        }
                        displayItemNum(binding.navView, 2, count);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        if (throwable != null) {
                            Toast.makeText(MainActivity.this, throwable.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }));

    }

    @SuppressLint("RestrictedApi")
    public void displayItemNum(final BottomNavigationView mBottomNavigationView, final int mPosition, final int mCount) {
        try {
            final int maxSize = mBottomNavigationView.getItemIconSize();
            if (mPosition > maxSize || mPosition < 0) {
                return;
            }
            final BottomNavigationMenuView menuView = (BottomNavigationMenuView) mBottomNavigationView.getChildAt(0);
            final View mTab = menuView.getChildAt(mPosition);
            final BottomNavigationItemView itemView = (BottomNavigationItemView) mTab;
            View mBadge = itemView.getChildAt(3);
            if (mBadge == null) {
                //避免重复添加创建
                mBadge = LayoutInflater.from(mBottomNavigationView.getContext()).inflate(R.layout.bottom_bar_item_badge, menuView, false);
                itemView.addView(mBadge);
            }
            final TextView mTv = mBadge.findViewById(R.id.tv_msg_count);
            if (mCount <= 0) {
                mTv.setVisibility(View.GONE);
                mTv.setText(String.format("%s", mCount));
            } else {
                mTv.setVisibility(View.VISIBLE);
                if (mCount > 99) {
                    mTv.setText(String.format("%s+", 99));
                } else {
                    mTv.setText(String.format("%s", mCount));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}